<template>
  <div id="client">
    <p style="position: relative; right: 180px; scale: 0.8; width: 1700px">
      <span class="demonstration" style="margin-left: 20px">开票日期：</span>
      <el-date-picker
        v-model="invoicingDate"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        @change="invoicingDateChange"
      >
      </el-date-picker>
      &nbsp;&nbsp;&nbsp;
      <span class="demonstration" style="margin-left: 20px">单据日期：</span>
      <el-date-picker
        v-model="DjDateRange"
        type="daterange"
        align="right"
        unlink-panels
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="handleDateChange2"
      >
      </el-date-picker>
      &nbsp;&nbsp;&nbsp; 单据编号：<el-input
        style="width: 180px; margin-left: 10px; margin-right: 20px"
        placeholder="单据编号"
        v-model="select.documentNumber"
        clearable
      >
      </el-input>
      &nbsp;&nbsp;&nbsp; 登记人<el-select
        style="width: 180px; margin-left: 10px; margin-right: 20px"
        placeholder="请选择"
        v-model="select.RegistrantsId"
        clearable
      >
        <el-option
          v-for="item in employee"
          :key="item.employeeId"
          :label="item.employeeName"
          :value="item.employeeId"
        >
        </el-option>
      </el-select>
    </p>

    <p style="position: relative; right: 180px; scale: 0.8; width: 1700px">
      &nbsp;&nbsp;&nbsp;供应商：<el-input
        style="width: 180px; margin-left: 10px; margin-right: 20px"
        placeholder="请选择"
        v-model="proName"
        clearable
      ></el-input>
      <el-button
        style="margin-left: -20px; margin-right: 10px"
        @click="dialogShow = true"
        >...</el-button
      >

      &nbsp;&nbsp;&nbsp; 业务员<el-select
        style="width: 180px; margin-left: 10px; margin-right: 20px"
        placeholder="请选择"
        v-model="select.yid"
        clearable
      >
        <el-option
          v-for="item in employee"
          :key="item.employeeId"
          :label="item.employeeName"
          :value="item.employeeId"
        >
        </el-option>
      </el-select>
      &nbsp;&nbsp;&nbsp; 发票号：<el-input
        style="width: 180px; margin-left: 10px; margin-right: 20px"
        placeholder="单据编号"
        v-model="select.invoiceNumber"
        clearable
      >
      </el-input>
      &nbsp;&nbsp;&nbsp; 发票抬头：<el-input
        style="width: 180px; margin-left: 10px; margin-right: 20px"
        placeholder="单据编号"
        v-model="select.invoiceTitle"
        clearable
      >
      </el-input>

      <el-button type="primary" @click="selectPage(1, 100)">查询</el-button>
    </p>
    <el-divider></el-divider>
    <div style="float: right; margin-bottom: 10px">
      &nbsp;&nbsp;&nbsp;
      <el-button @click="goto('Invoice')">采购发票登记</el-button>
      <el-button>导出</el-button>
      <el-button type="danger" @click="del(selectedRows)">删除</el-button>
    </div>
    <el-table
      height="400px"
      :data="pageInfo ? pageInfo.list : []"
      :row-class-name="tableRowClassName"
      border
      style="width: 100%; font-size: 13px"
      @selection-change="handleSelectionChange"
      show-summary
      :summary-method="summaryMethod"
    >
      <el-table-column type="selection" width="55"> </el-table-column>

      <el-table-column
        prop="purchaseOrders.createDate"
        label="单据日期"
        width="150"
      >
      </el-table-column>

      <el-table-column
        prop="purchaseOrders.documentNumber"
        label="单据编号"
        width="320"
      >
      </el-table-column>
      <el-table-column
        prop="purchaseOrders.orderNumber"
        label="关联购货订单号"
        width="120"
      >
      </el-table-column>
      <el-table-column prop="purchaseOrders.proName" label="供应商" width="120">
      </el-table-column>
      <el-table-column
        prop="invoice.registrantsName"
        label="登记人"
        width="120"
      >
      </el-table-column>
      <el-table-column
        prop="invoice.dateOrderMade"
        label="制单日期"
        width="120"
      >
      </el-table-column>
      <el-table-column prop="purchaseOrders.quantity" label="数量" width="120">
        <template slot-scope="scope">
          {{ Math.abs(scope.row.purchaseOrders.quantity) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="purchaseOrders.amount"
        label="价税合计"
        width="120"
      >
        <template slot-scope="scope">
          {{ Math.abs(scope.row.purchaseOrders.amount) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="purchaseOrders.writtenOffAmount"
        label="已付款"
        width="120"
      >
        <template slot-scope="scope">
          {{ Math.abs(scope.row.purchaseOrders.writtenOffAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="付款状态" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.purchaseOrders.purType == 1">
            <div v-if="scope.row.purchaseOrders.writtenOffAmount == 0">
              未付款
            </div>
            <div
              v-else-if="
                scope.row.purchaseOrders.writtenOffAmount ===
                scope.row.purchaseOrders.amount
              "
            >
              全部付款
            </div>
            <div v-else>部分付款</div>
          </span>
          <span v-else>
            <div v-if="scope.row.purchaseOrders.writtenOffAmount == 0">
              未退款
            </div>
            <div
              v-else-if="
                scope.row.purchaseOrders.writtenOffAmount ===
                scope.row.purchaseOrders.amount
              "
            >
              全部退款
            </div>
            <div v-else>部分退款</div>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="invoice.invoicingDate"
        label="开票日期"
        width="120"
      >
      </el-table-column>
      <el-table-column prop="invoice.invoicingDate" label="销售方" width="120">
      </el-table-column>

      <el-table-column prop="thisInvoicedAmount" label="开票金额" width="120">
        <template slot-scope="scope">
          {{ Math.abs(scope.row.thisInvoicedAmount) }}
        </template>
      </el-table-column>

      <el-table-column prop="invoice.invoiceNumber" label="发票号" width="120">
      </el-table-column>

      <el-table-column prop="invoice.invoiceTitle" label="发票抬头" width="120">
      </el-table-column>
      <el-table-column
        prop="invoice.invoicingNotes"
        label="开票备注"
        width="120"
      >
      </el-table-column>
      <el-table-column
        prop="purchaseOrders.remark"
        label="整单备注"
        width="120"
      >
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="beforDel(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-left: 500px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageInfo ? pageInfo.pageNum : 1"
      :page-sizes="[100, 200, 300, 400]"
      :page-size="pageInfo ? pageInfo.pageSize : 100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo ? pageInfo.total : 0"
    >
    </el-pagination>

    <el-dialog top="20px" title="选择供应商" :visible.sync="dialogShow">
      <ProviderChoose ref="choosePro" :dialogShow="dialogShow" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">取 消</el-button>
        <el-button type="primary" @click="yes">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ProviderChoose from "../public_com/ProviderChoose.vue";

function getNestedValue(obj, path) {
  return path.split(".").reduce((o, k) => (o || {})[k], obj);
}

export default {
  name: "InDoc",
  components: {
    ProviderChoose,
  },
  data() {
    return {
      select: {
        invoicingDate1: "",
        invoicingDate2: "",
        startDate2: "",
        endDate2: "",
        documentNumber: "",
        proId: "",
        yid: "",
        invoiceNumber: "",
        invoiceTitle: "",
        RegistrantsId: "",
      },
      pageInfo: "",
      employee: [],
      proName: "",
      invoicingDate: [],
      DjDateRange: [],
      dialogShow: false,
      selectedRows: [],
    };
  },
  methods: {
    beforDel(thisRow){
      const row = [thisRow];
      this.del(row)
    },
    del(row) {
      this.$confirm("您确认要删除选中的采购开票记录么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios({
            url: "/purchase/invoiceDetail/delInvoiceDetail",
            method: 'POST',
            data: row,
          }).then((rs) => {
            if (rs.data.code === 200) {
              this.selectPage(1,100)
              this.$message({
                showClose: true,
                message: "删除成功",
                type: "success",
              });
            } else {
              this.$message({
                showClose: true,
                message: "删除失败",
                type: "error",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSelectionChange(selectedRows) {
      this.selectedRows = selectedRows;
    },
    summaryMethod({ columns, data }) {
      const sums = {};
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }

        const key = column.property;

        if (!key) {
          sums[index] = "";
          return;
        }

        const values = data.map((item) => {
          const value = getNestedValue(item, key);
          return Number(value);
        });

        if (
          key === "purchaseOrders.quantity" ||
          key === "purchaseOrders.amount" ||
          key === "purchaseOrders.writtenOffAmount" ||
          key === "thisInvoicedAmount"
        ) {
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + value;
              } else {
                return prev;
              }
            }, 0);
          } else {
            sums[index] = "";
          }
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.purchaseOrders.purType === 2) {
        return "row-red";
      }
      return "";
    },
    handleSizeChange(newSize) {
      console.log(`每页 ${newSize} 条`);
      this.findAll(1, newSize);
    },
    handleCurrentChange(newPage) {
      console.log(`当前页: ${newPage}`);
      this.findAll(newPage, this.pageInfo.pageSize);
    },
    selectEm() {
      this.axios({
        url: "/info/employee/listAll",
      }).then((rs) => {
        this.employee = rs.data.list;
      });
    },
    yes() {
      this.dialogShow = false;
      var list = this.$refs.choosePro.selectionList;
      if (list.length <= 0) {
        this.proName = "";
        this.select.proId = "";
        return;
      }
      this.proName = list[0].providerName;
      this.select.proId = list[0].providerId;
    },
    goto(to) {
      this.$router.push(to);
    },
    invoicingDateChange(value) {
      if (value) {
        this.select.invoicingDate1 = value[0]; // 起始日期
        this.select.invoicingDate2 = value[1]; // 结束日期
      } else {
        this.select.invoicingDate1 = ""; // 起始日期
        this.select.invoicingDate2 = ""; // 结束日期
      }
    },
    selectPage(pageNum, pageSize) {
      console.log(this.select);

      this.axios
        .get("/purchase/invoiceDetail/getPage", {
          params: {
            pageNum,
            pageSize,
            ...this.select,
          },
          paramsSerializer: function (params) {
            return new URLSearchParams(params).toString();
          },
        })
        .then((rs) => {
          console.log(rs);
          if (rs.data.pageInfo) {
            this.pageInfo = rs.data.pageInfo;
          }
        });
    },
    handleDateChange2(value) {
      if (value) {
        this.select.startDate2 = value[0]; // 起始日期
        this.select.endDate2 = value[1]; // 结束日期
      } else {
        this.select.startDate2 = ""; // 起始日期
        this.select.endDate2 = ""; // 结束日期
      }
    },
  },
  created() {
    this.selectEm();
    this.selectPage(1, 100);
  },
};
</script>

<style scope>
.el-button el-button--default el-popover__reference {
  margin-right: 20px;
}

tr {
  border: 1px solid black;
}
</style>